package com.sg.xy.controller;

import com.sg.xy.dao.CodeDao;
import com.sg.xy.feign.EmailFeign;
import com.sg.xy.pojo.AuthCode;
import com.sg.xy.service.AuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/code")
public class CodeController {
    @Autowired
    private AuthCodeService codeService;

    @Autowired
    private CodeDao codeDao;

    @Autowired
    private EmailFeign emailFeign;

    /**
     * ⽣成验证码并发送到对应邮箱，成功true，失败
     * false
     *
     * @param email
     * @return
     */
    @GetMapping("/create/{email}")
    public Object create(@PathVariable String email) {
        AuthCode authCode = codeService.getByEmail(email);
        long l = System.currentTimeMillis();
        if (authCode != null && authCode.getExpiretime().getTime() > l) {
            return "1分钟之内只能发一次";
        }
        String code = (int)((Math.random() * 9 + 1) * 100000) + "";
        authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setCreatetime(new Date(l));
        authCode.setExpiretime(new Date(l + 30 * 1000));
        authCode.setEmail(email);
        Boolean validate = emailFeign.validate(email, code);
        if (validate) {
            codeDao.save(authCode);
        }
        return validate;
    }
    /**
     * 校验验证码是否正确，0正确1错误2超时
     *
     * @param email
     * @return
     */
    @GetMapping("/validate/{email}/{code}")
    public String validate(@PathVariable String email, @PathVariable String code) {
        AuthCode authCode = codeService.getByEmail(email);
        if (authCode == null) {
            return "1";
        }
        if (authCode.getCreatetime().getTime() + 2 * 60 * 1000 < System.currentTimeMillis()) {
            return "2";
        }
        return "0";
    }

}
